﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 工位管理服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class stationService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<station> _stationRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public stationService(SqlSugarRepository<station> stationRep, ISqlSugarClient sqlSugarClient)
    {
        _stationRep = stationRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询工位管理 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询工位管理")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<stationOutput>> Page(PagestationInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _stationRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.StationCoding.Contains(input.Keyword) || u.StationName.Contains(input.Keyword) || u.StationDescribe.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.StationCoding), u => u.StationCoding.Contains(input.StationCoding.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.StationName), u => u.StationName.Contains(input.StationName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.StationDescribe), u => u.StationDescribe.Contains(input.StationDescribe.Trim()))
            .WhereIF(input.ProductionId != null, u => u.ProductionId == input.ProductionId)
            .WhereIF(input.ProcessId != null, u => u.ProcessId == input.ProcessId)
            .LeftJoin<production>((u, production) => u.ProductionId == production.Id)
            .LeftJoin<Processmanage>((u, production, process) => u.ProcessId == process.Id)
            .Select((u, production, process) => new stationOutput
            {
                Id = u.Id,
                StationCoding = u.StationCoding,
                StationName = u.StationName,
                ProductionId = u.ProductionId,
                ProductionFkDisplayName = $"{production.ProductionName}",
                ProcessId = u.ProcessId,
                ProcessFkDisplayName = $"{process.processname}",
                StationDescribe = u.StationDescribe,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取工位管理详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取工位管理详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<station> Detail([FromQuery] QueryByIdstationInput input)
    {
        return await _stationRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加工位管理 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加工位管理")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddstationInput input)
    {
        var entity = input.Adapt<station>();
        return await _stationRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新工位管理 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新工位管理")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdatestationInput input)
    {
        var entity = input.Adapt<station>();
        await _stationRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除工位管理 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除工位管理")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeletestationInput input)
    {
        var entity = await _stationRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _stationRep.FakeDeleteAsync(entity);   //假删除
        //await _stationRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除工位管理 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除工位管理")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")] List<DeletestationInput> input)
    {
        var exp = Expressionable.Create<station>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _stationRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _stationRep.FakeDeleteAsync(list);   //假删除
        //return await _stationRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDatastationInput input)
    {
        var productionIdData = await _stationRep.Context.Queryable<production>()
            .InnerJoinIF<station>(input.FromPage, (u, r) => u.Id == r.ProductionId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.ProductionName}"
            }).ToListAsync();
        var processIdData = await _stationRep.Context.Queryable<Processmanage>()
            .InnerJoinIF<station>(input.FromPage, (u, r) => u.Id == r.ProcessId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.processname}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "productionId", productionIdData },
            { "processId", processIdData },
        };
    }
    
    /// <summary>
    /// 导出工位管理记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出工位管理记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PagestationInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportstationOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "工位管理导出记录");
    }
    
    /// <summary>
    /// 下载工位管理数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载工位管理数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportstationOutput>(), "工位管理导入模板", (_, info) =>
        {
            if (nameof(ExportstationOutput.ProductionFkDisplayName) == info.Name) return _stationRep.Context.Queryable<production>().Select(u => $"{u.ProductionName}").Distinct().ToList();
            if (nameof(ExportstationOutput.ProcessFkDisplayName) == info.Name) return _stationRep.Context.Queryable<Processmanage>().Select(u => $"{u.processname}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入工位管理记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入工位管理记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportstationInput, station>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 所属产线
                    var productionIdLabelList = pageItems.Where(x => x.ProductionFkDisplayName != null).Select(x => x.ProductionFkDisplayName).Distinct().ToList();
                    if (productionIdLabelList.Any()) {
                        var productionIdLinkMap = _stationRep.Context.Queryable<production>().Where(u => productionIdLabelList.Contains($"{u.ProductionName}")).ToList().ToDictionary(u => $"{u.ProductionName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.ProductionId = productionIdLinkMap.GetValueOrDefault(e.ProductionFkDisplayName ?? "");
                            if (e.ProductionId == null) e.Error = "所属产线链接失败";
                        });
                    }
                    // 链接 工序
                    var processIdLabelList = pageItems.Where(x => x.ProcessFkDisplayName != null).Select(x => x.ProcessFkDisplayName).Distinct().ToList();
                    if (processIdLabelList.Any()) {
                        var processIdLinkMap = _stationRep.Context.Queryable<Processmanage>().Where(u => processIdLabelList.Contains($"{u.processname}")).ToList().ToDictionary(u => $"{u.processname}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.ProcessId = processIdLinkMap.GetValueOrDefault(e.ProcessFkDisplayName ?? "");
                            if (e.ProcessId == null) e.Error = "工序链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<station>>();
                    
                    var storageable = _stationRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.StationCoding?.Length > 32, "编码长度不能超过32个字符")
                        .SplitError(it => it.Item.StationName?.Length > 32, "名称长度不能超过32个字符")
                        .SplitError(it => it.Item.StationDescribe?.Length > 32, "描述长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
